import Vue from 'vue'
// import axios from 'axios'
import axios from '../axios'
import Router from 'vue-router'
import Home from '../views/Home.vue'
import Index from '../views/Index.vue'
// import Menu from '../views/sys/Menu.vue'
// import Role from '../views/sys/Role.vue'
// import User from '../views/sys/User.vue'
// import Dict from '../views/sys/Dict.vue'
import store from '../store'
// 解决ElementUI导航栏中的vue-router在3.0版本以上重复点菜单报错问题
const originalPush = Router.prototype.push
Router.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(Router)

const routes = [{
  path: '/',
  name: 'Home',
  children: [{
    path: '/index',
    name: 'Index',
    component: Index
  },
  {
    path: '/userCenter',
    name: 'UserCenter',
    title: '个人中心',
    component: () => import('@/views/UserCenter.vue')
  }
    // {
    //   path: '/sys/menus',
    //   name: 'SysMenu',
    //   component: Menu
    // },
    // {
    //   path: '/sys/roles',
    //   name: 'SysRole',
    //   component: Role
    // },
    // {
    //   path: '/sys/users',
    //   name: 'SysUser',
    //   component: User
    // },
    // {
    //   path: '/sys/dicts',
    //   name: 'SysDict',
    //   component: Dict
    // }
  ],
  component: Home
},
{
  path: '/login',
  name: 'Login',
  component: () => import('@/views/Login.vue')
}
]
const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  let hasRoute = store.state.menus.hasRoute
  let token = localStorage.getItem('token')
  if (to.path === '/login' || to.path === '/index') {
    next()
  } else if (!token) {
    next({
      path: '/login'
    })
  } else if (token && !hasRoute) {
    axios.get('/sys-menu/nav', {
      headers: {
        Authorization: localStorage.getItem('token')
      }
    }).then(res => {
      // menuList
      store.commit('setMenuList', res.data.data.nav)
      // permList
      store.commit('setPermList', res.data.data.authoritys)
      // 动态绑定路由
      let newRoutes = router.options.routes

      res.data.data.nav.forEach(menu => {
        if (menu.children) {
          menu.children.forEach(e => {
            // 转成路由
            let route = menuToRouter(e)
            // 把路由添加到路由管理中
            if (route) {
              newRoutes[0].children.push(route)
            }
          })
        }
      })
      router.addRoutes(newRoutes)
      hasRoute = true
      store.commit('changeRouteState', hasRoute)
    })
  }

  next()
})
const menuToRouter = (menu) => {
  if (!menu.component) {
    return null
  }
  let route = {
    name: menu.name,
    path: menu.path,
    meta: {
      icon: menu.icon,
      title: menu.title
    }
  }
  route.component = () => import('@/views/' + menu.component + '.vue')
  return route
}
export default router
